<!-- 门店入驻 -->
<template>
	<view class="apply-commission-wrap page_box">
		<!-- 标题栏 -->
		<view class="head-box"></view>

		<!-- 表单 -->
		<view class="apply-form content_box">

			<view class="cu-form-group">
				<view class="title">姓名</view>
				<input type="text" placeholder="请输入姓名" v-model="model.name"></input>
			</view>
			
			<view class="cu-form-group">
				<view class="title">手机号</view>
				<input type="text" placeholder="请输入手机号" v-model="model.mobile"></input>
			</view>

			<view class="cu-form-group">
				<view class="title">店铺名称</view>
				<input type="text" placeholder="请输入店铺名称" v-model="model.shopname"></input>
			</view>
				
			<view class="cu-form-group">
				<view class="title">店铺类型</view>
				<picker @change="pickerChange" :value="categoryIndex" :range="typelist" range-key="name">
					<view class="picker">{{ categoryIndex > -1 ? typelist[categoryIndex].name : '点击选择分类' }}</view>
				</picker>
			</view>
				
			<view class="cu-form-group-upload">
				<view class="title">店铺头像上传</view>
				<view class="flex align-center flex-wrap">
					<view class="margin-right-xs position-relative"
					v-if="model.images_md.length > 0"
						v-for="(item, index) in model.images_md"
						:key="index">
						<view class="uploaditem" @tap="handlePreview(1, index)">
							<image :src="item.fullurl" mode="widthFix"></image>
						</view>
						<view class="tag" @tap="handleDelImage(1, index)">
							<image src="/static/images/delete.png" style="width: 46rpx;height: 46rpx;"></image>
						</view>
					</view>
					
					<view v-if="model.images_md.length < 1" @tap="handleImage(1)">
						<view class="uploaditem">
							<view class="text-lg text-gray">
								<text class="wlIcon-tianjia"></text>
								<view v-if="model.images_md.length === 0" class="margin-top-xs text-sm">添加图片</view>
								<view v-else class="margin-top-xs text-sm">继续添加</view>
							</view>
						</view>
					</view>
				</view>
			</view>
				
			<view class="cu-form-group">
				<view class="title">营业执照编号</view>
				<input type="text" placeholder="请输入营业执照编号" v-model="model.number"></input>
			</view>
				
			<view class="cu-form-group-upload">
				<view class="title">营业执照上传</view>
				<view class="flex align-center flex-wrap">
					<view class="margin-right-xs position-relative"
					v-if="model.images_zz.length > 0"
						v-for="(item, index) in model.images_zz"
						:key="index">
						<view class="uploaditem" @tap="handlePreview(2, index)">
							<image :src="item.fullurl" mode="widthFix"></image>
						</view>
						<view class="tag" @tap="handleDelImage(2, index)">
							<image src="/static/images/delete.png" style="width: 46rpx;height: 46rpx;"></image>
						</view>
					</view>
					
					<view v-if="model.images_zz.length < 1" @tap="handleImage(2)">
						<view class="uploaditem">
							<view class="text-lg text-gray">
								<text class="wlIcon-tianjia"></text>
								<view v-if="model.images_zz.length === 0" class="margin-top-xs text-sm">添加图片</view>
								<view v-else class="margin-top-xs text-sm">继续添加</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		
			<view class="cu-form-group area">
				<view class="click" @tap="btnClick"></view>
				<view class="title">所在地区</view>
				<input type="text" :value="model.area" placeholder="选择地区" disabled />
			</view>
			
			<view class="cu-form-group align-start">
				<view class="title">详细地址</view>
				<!-- 1.1.5升级 -->
				<textarea 
				maxlength="-1" 
				@input="getInputtips"
				@focus="focusInputtips" 
				@confirm="confirmInputtips" 
				@blur="blurInputtips"
				:placeholder-style="addressData.adcode==''?'color: #bbb':''" 
				:adjust-position="false" 
				v-model="addressData.address_full"
				:disabled="addressData.adcode==''?true:false" 
				:placeholder="addressData.adcode==''?'还没有选择地区哦~ 选择地区后完成此项':'支持智能联想，输入小区名试试~'"/>
			</view>

			<scroll-view scroll-y="true" class="tipsScroll"  v-if="!addressType">
				<view class="item" v-for="(item,index) in addressList.tips" :key="index" @tap="addressTisp(item)">
					<view>{{item.address}}</view>
					<text>{{item.name}}</text>
				</view>
			</scroll-view>
			
	<!-- 		<view class="cu-form-group align-start">
				<view class="title">店铺简介</view>
				<textarea placeholder="请输入店铺简介" class="textarea-style" v-model="model.bio"></textarea>
			</view>
			
			<view class="cu-form-group align-start">
				<view class="title">店铺介绍</view>
				<textarea placeholder="请输入店铺介绍" class="textarea-style" v-model="model.content"></textarea>
			</view> -->
			
	
			<view class="agreement flex align-center">
				<checkbox-group :class="model.agreement == 1 ? 'shake-horizontal' : ''" class="auth-clause flex align-center justify-center" @change="CheckboxChange">
					<checkbox class="green" style="transform: scale(0.7);"
					:class="model.agreement == 2 ? 'checked' : ''" 
					:checked="model.agreement == 2 ? true : false" 
					value="2" />
					<view class="agreement-text" @tap="toProtocol">勾选代表同意《申请协议》</view>
				</checkbox-group>
			</view>
			
			<view class="u-flex u-row-center u-col-center">
				<button class="u-reset-button save-btn" @tap="onSubmitAdd" v-if="!is_store">
					确认提交
				</button>
				<button class="u-reset-button save-btn" @tap="onSubmitEdit" v-if="is_store">
					确认更改
				</button>
			</view>
		</view>

		<!-- 权限验证 -->
		<uni-popup ref="authpopup" :mask-click="false">
			<view class="notice-modal">
				<view class="img-wrap"><image class="notice-img" :src="authNotice.img" mode=""></image></view>
				<view class="notice-title">{{ authNotice.title }}</view>
				<view class="notice-detail">{{ authNotice.detail || '' }}</view>
				<button class="u-reset-button notice-btn" @tap="onAuthBtn(authNotice.btnPath)">
					{{ authNotice.btnText }}
				</button>
				<button class="u-reset-button back-btn" @tap="$wanlshop.back()">返回</button>
			</view>
		</uni-popup>
		
		
		<wanl-address ref='wanlAddress' @selectAddress="successSelectAddress"></wanl-address>
		
	</view>
</template>

<script>
// import Auth from '@/shopro/permission/index.js';
import { mapMutations, mapActions, mapState, mapGetters } from 'vuex';
import { MAP_KEY, BASE_URL } from '@/env.js';
export default {
	components: {},
	data() {
		return {
			authNotice: {},
			categoryIndex: -1,
			placeholderStyle: 'font-size: 28rpx;color:#c4c4c4;',
			model: {
				type: -1, //店铺类型id，0个体，1企业
				shopname: '', //门店名称
				name: '', //姓名
				number: '', //营业执照编号
				mobile: '', //手机号
				images_md: [], //门店图片
				images_zz: [], //营业执照上传
				bio: '', //门店简介
				content: '', //店铺介绍
				area: '',
				address: '', //门店地址
				latitude: '', //纬度
				longitude: '', //京都
				agreement: 1,
				avatar:'', //店铺头像
				image:'', //营业执照
			},
			typelist: [
				{
					value:0,
					name:'个体',
				},
				{
					value:1,
					name:'企业',
				},
			],
			is_store: '',
			addressData: {
				name: '',
				mobile: '',
				default: 0,
				//地区
				country: '', // 国家
				province: '', //省份
				city: '', // 城市
				citycode: '', // 城市代码
				district: '', // 县
				adcode: '', // 地区代码
				formatted_address: '', //详细地区
				//详情
				address: '', //详细地址
				address_name: '', // 地址名称
				address_full: '', // 完整地址名称
				location: '' ,//经纬度
			},
			addressList: {
				location: '',
				adcode: '',
				tips: {}
			},
			addressType:true,
			userInfo:{},
		};
	},
	onLoad() {
		this.getUserInfo();
	},
	methods: {
		getUserInfo(){
			uni.request({
				url: '/user/info',
				method: 'POST',
				success: res => {
					res = res.res;
					if(res.code == 1){
						this.userInfo = res.data;
						this.getStoreInfo();
					}
				}
			});
		},
		getStoreInfo() {
			let that = this;
			uni.request({
				url: '/user/applyshopshow',
				data: {},
				success: res => {
					res = res.res
					if (res.code === 1 && res.data && res.data.name) {
						this.authStatus(res.data);
						this.model.name = res.data.name;
						this.model.mobile = res.data.mobile;
						this.model.shopname = res.data.shopname;
						
						let tmp = {
							fullurl:res.data.image_text,
							url:res.data.image,
						};
						this.model.images_zz.push(tmp);
						
						tmp = {
							fullurl:res.data.avatar_text,
							url:res.data.avatar,
						};
						this.model.images_md.push(tmp);
						
						this.model.latitude = res.data.latitude;
						this.model.longitude = res.data.longitude;
						this.model.number = res.data.number;
						
						this.model.address = res.data.address;
						this.addressData.address_full = res.data.address;
						this.categoryIndex = res.data.type;
						this.model.type = res.data.type;
						this.model.area = `${res.data.province}-${res.data.city}-${res.data.area}`;
						
						this.model.province = res.data.province;
						this.model.city = res.data.city;
						this.model.district = res.data.area;

					}
				}
			});
			
		},
		//选择店铺类型
		pickerChange(e) {
			this.categoryIndex = e.detail.value;
			this.model.type = this.typelist[this.categoryIndex].value;
		},

		// 弹窗按钮
		onAuthBtn(path) {
			path && this.$wanlshop.to(path);
			this.$refs.authpopup.close();
		},
		// 地址选择
		async chooseLocation() {
			let authState = await new Auth('userLocation').check();
			authState &&
				uni.chooseLocation({
					success: res => {
						this.model.latitude = res.latitude;
						this.model.longitude = res.longitude;
						this.getLocationInfo();
					},
					fail: err => {
						console.log(err);
					}
				});
		},

		//逆坐标解析
		async getLocationInfo() {
			// 116.553983,39.934507
			// https://restapi.amap.com/v3/geocode/regeo?location=116.553983,39.934507&key=64163282028477f901a29d6d79dee15e
			// console.log('this.model.longitude :>> ', this.model.longitude);
			// console.log('this.model.latitude :>> ', this.model.latitude);
			// console.log('MAP_KEY :>> ', MAP_KEY);
			this.chooseAddress = '定位中...';
			const [error, res] = await uni.request({
				url: `https://restapi.amap.com/v3/geocode/regeo?location=${this.model.longitude},${
					this.model.latitude
				}&key=${MAP_KEY}`
			});
		
			if (res.data.status === '1') {
				// this.model.area = res.data.info;
				const addressComponent = res.data.regeocode.addressComponent;
				this.model.area_id = addressComponent.adcode;
				this.model.area = `${addressComponent.province}-${
					addressComponent.city.length ? addressComponent.city : addressComponent.province
				}-${addressComponent.district}`;
				this.model.address = res.data.regeocode.formatted_address.replace(
					`${addressComponent.province}${addressComponent.city}${addressComponent.district}`,
					''
				);
			} else {
				console.log('%c逆地址解析失败，请检查是否在env中配置地图key', 'color:green;background:yellow');
			}
		},

		// 勾选同意
		onAgreement(e) {
			console.log('e :>> ', e);
			this.model.agreement = e.value;
		},

		// 跳转门店协议
		toProtocol() {
			this.initStore.protocol && this.$wanlshop.to('/pages/public/richtext', { id: this.initStore.protocol });
		},

		// 状态鉴权
		authStatus(data) {
			switch (String(data.verify)) {
				//2=提交审核,3=通过,4=未通过
				case '2':
					this.$refs.authpopup.open();
					this.model = { ...this.model, ...data };
					this.authNotice = {
						img: BASE_URL + '/assets/img/auth_check.png',
						title: '正在审核中',
						detail: data.refuse,
						btnText: '修改信息',
						btnPath: ''
					};
					break;
				case '4':
					this.$refs.authpopup.open();
					this.model = { ...this.model, ...data };
					this.authNotice = {
						img: BASE_URL + '/assets/img/auth_reject.png',
						title: '您的申请已被驳回！',
						detail: data.refuse,
						btnText: '重新申请',
						btnPath: ''
					};
					break;
				case '3':
					this.$refs.authpopup.close();
					break;

				default:
			}
		},
		//添加
		onSubmitAdd() {
			let that = this;
			// this.$wanlshop.msg('系统正在开发中');
			// return false;
			
			if(this.checkForm()){
				let request = this.setRequest();
				
				uni.request({
					url: '/user/applyshop',
					data: request,
					method: 'POST',
					success: res => {
						res = res.res
						if (res.code === 1) {
							uni.showToast({
								title: res.msg,
								icon:'none',
								success: () => {
									that.$wanlshop.back();
								}
							});
						}
					}
				});
			}
		},
		//修改
		onSubmitEdit() {
			if(this.checkForm()){
				let that = this;
				let request = this.setRequest();
								
				uni.request({
					url: '/user/applyshop',
					data: request,
					method: 'POST',
					success: res => {
						res = res.res
						if (res.code === 1) {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								success: () => {
									that.$wanlshop.back();
								}
							});
						}
					}
				});
			}
		},
		setRequest(){
			let request = JSON.parse(JSON.stringify(this.model));
			request.avatar = request.images_md[0].url;
			request.image = request.images_zz[0].url;
			request.address = this.addressData.address_full;
			request.area = request.district;
			
			delete(request.district);
			delete(request.bio);
			delete(request.content);
			delete(request.images_md);
			delete(request.images_zz);
			delete(request.agreement);
			
			return request;
		},
		checkForm(){
			let that = this;
	
			if (!that.model.name) {
				this.$wanlshop.msg('请输入姓名');
				return false;
			}
			
			if (!that.model.mobile) {
				this.$wanlshop.msg('请输入手机号');
				return false;
			}
			
			if(!/^1[23456789]\d{9}$/.test(that.model.mobile)){
				this.$wanlshop.msg('手机号格式错误');
				return false;
			}
			
			if (!that.model.shopname) {
				this.$wanlshop.msg('请输入店铺名称');
				return false;
			}
			
			if (that.model.type < 0) {
				this.$wanlshop.msg('请选择店铺类型');
				return false;
			}
			
			if (!that.model.images_md.length) {
				this.$wanlshop.msg('请上传店铺头像');
				return false;
			}
			
			if (!that.model.number) {
				this.$wanlshop.msg('请输入营业执照编号');
				return false;
			}
			
			if (!that.model.images_zz.length) {
				this.$wanlshop.msg('请上传营业执照');
				return false;
			}
			
			if (!that.model.area) {
				this.$wanlshop.msg('请选择所在地区');
				return false;
			}
			
			if (!that.addressData.address_full) {
				this.$wanlshop.msg('请输入详细地址');
				return false;
			}
			
			if (this.model.agreement != 2) {
				this.$wanlshop.msg('请勾选协议');
				return false;
			}
			
			return true;
		},
		handleImage(type) {
			let that = this;
			let count = 1;
			uni.chooseImage({
				count: count, //默认9
				sizeType: ["compressed"], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ["album"], //从相册选择
				crop: {
					quality: 60
				},
				success: res => {
					for (let i = 0; i < res.tempFilePaths.length; i++) {
						this.uploadImage(res.tempFilePaths[i]).then(uploadImageRes=>{
							if(type===1){
								that.model.images_md.push(uploadImageRes);
							}
							
							if(type===2){
								that.model.images_zz.push(uploadImageRes);
							}
						});
					}
				}
			});
			
		},
		// 图片处理-上传图片
		async uploadImage(url) {
			const that = this;
			return new Promise((resolve, reject) => {
				uni.request({
					url: '/wanlshop/common/uploadData',
					success: updata => {
						uni.uploadFile({
							url: updata.data.uploadurl,
							filePath: url,
							name: 'file',
							formData: updata.data.storage == 'local' ? null : updata.data.multipart,
							success: res => {
								console.log(JSON.parse(res.data).data);
								that.$wanlshop.msg("上传成功");
								resolve(JSON.parse(res.data).data);
							},
							fail: error =>{
								that.$wanlshop.msg(JSON.parse(error.data).msg);
							}
						});
					}
				});
				
			}).catch(e => {
				console.log(e);
			});
		},
		handlePreview(type, index) {
			let tmps = [];
			if(type==1){
			    this.model.images_md.forEach((value) =>{
					tmps.push(value.fullurl);  
				});
			}
			
			if(type==2){
				this.model.images_zz.forEach((value) =>{
					tmps.push(value.fullurl);  
				});
			}
			
			uni.previewImage({
				urls:tmps,
				current: tmps[index],
				indicator: 'number'
			});
		},
		handleDelImage(type, index) {
			if(type===1){
				this.model.images_md.splice(index, 1);
			}
			
			if(type===2){
				this.model.images_zz.splice(index, 1);
			}
		},
		btnClick() {
			uni.pageScrollTo({
				scrollTop: 0, // 滚动到页面的目标位置（单位px）
				duration: 300 // 滚动动画的时长，默认300ms，单位 ms
			});
				
			this.$refs.wanlAddress.show()
		},
		successSelectAddress(address) {
			this.addressData.country = address.country;
			this.addressData.province = address.province;
			this.addressData.city = address.city;
			this.addressData.citycode = address.citycode;
			this.addressData.district = address.district;
			this.addressData.formatted_address = address.formatted_address;
			this.addressData.location = address.location;
			this.addressData.adcode = address.adcode;
			this.addressList.location = address.location;
			this.addressList.adcode = address.adcode;
	
			this.model.area = address.province+"-"+address.city+"-"+address.district;
			this.model.province = address.province;
			this.model.city = address.city;
			this.model.district = address.district;
			
			let arr = address.location.split(","); // 使用split()方法将字符串分割成数组
			this.model.longitude = arr[0]; //数字大的是经度
			this.model.latitude = arr[1];
		},
		//调用高德地图搜索相关地址
		getInputtips(event) {
			let keywords = event.detail.value;
			if (keywords) {
				uni.request({
					url: 'https://restapi.amap.com/v3/assistant/inputtips',
					data: {
						key: this.$wanlshop.config('amapkey'),
						keywords: keywords,
						location: this.addressList.location,
						city: this.addressList.adcode
					},
					success: (res) => {
						console.log("getInputtips",res);
						
						let addressList = [];
						// 1.1.8升级
						if(res.res.infocode == 10001){
							this.$wanlshop.msg('获取位置失败：错误' + res.res.info);
						}else{
							res.data.tips.forEach(item => {
								if (item.address.length == 0) {
									item.address = '暂未收录地址';
									item.location = '113.294701,22.666562';
								}
								addressList.push(item);
							});
						}
						this.addressList.tips = addressList;
					}
				});
			}
		},
		// 详细地址替换
		addressTisp(data) {
			this.addressData.adcode = data.adcode;
			this.addressData.address = data.address;
			this.addressData.address_name = data.name;
			// 1.0.5升级
			if(data.address){
				this.addressData.address_full = this.addressData.address_name + this.addressData.address;
			}
			this.addressData.location = data.location;
			this.addressType = true;
		
			let arr = data.location.split(","); // 使用split()方法将字符串分割成数组
			this.model.longitude = arr[0]; //数字大的是经度
			this.model.latitude = arr[1];
		},
		// 详细地址失去焦点
		blurInputtips(event) {
			this.addressData.address = event.detail.value;
			setTimeout(() => {
				this.addressType = true;
			}, 10);
		},
		// 详细地址已完成
		confirmInputtips(event) {
			this.addressType = true;
		},
		// 详细地址获取焦点
		focusInputtips(event) {
			this.addressType = false;
		},
		CheckboxChange(e) {
			this.model.agreement = e.detail.value;
		},
	}
};
</script>

<style lang="scss">
.apply-commission-wrap {
	background-color: #fff;
	.head-box {
		background: url('https://mjyv2.gsmjyjy.com/assets/img/store.jpg') no-repeat;
		background-size: 100% auto;
		height: 370rpx;
	}
}
// 表单
.apply-form {
	width: 750rpx;
	background: #ffffff;
	border-radius: 20rpx;
	padding: 30rpx;
	.agreement {
		margin-top: 20rpx;
		.agreement-text {
			font-size: 24rpx;
			font-weight: 500;
			color: #57ce16;
		}
	}
	.save-btn {
		width: 690rpx;
		line-height: 86rpx;
		// background: linear-gradient(90deg, #2dae9c, #6bc29e);
		// box-shadow: 0px 7rpx 11rpx 2rpx rgba(61, 179, 156, 0.34);
		background: linear-gradient(-90deg, #57ce16 0%, #88DD18 100%);
		box-shadow: 0px 7rpx 6rpx 0px rgba(205, 251, 176, 0.22);
		border-radius: 43rpx;
		font-weight: 500;
		color: #ffffff;
		margin: 30rpx 0;
	}
}

// 星期
.week-modal {
	.week-modal--head {
		height: 100rpx;
		border-bottom: 1rpx solid #ccc;

		.text-cancel {
			color: #ccc;
		}
		.text-green {
			color: #18b566;
		}
	}
	.week-modal--content {
		.week-btn {
			margin-right: 56rpx;
			margin-bottom: 30rpx;
			&:nth-of-type(4n) {
				margin-right: 0;
			}
		}
	}
}

// 提示
.notice-modal {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	width: 612rpx;
	min-height: 658rpx;
	background: #ffffff;
	padding: 30rpx;
	border-radius: 20rpx;
	.img-wrap {
		margin-bottom: 50rpx;
		.notice-img {
			width: 180rpx;
			height: 170rpx;
		}
	}
	.notice-title {
		font-size: 35rpx;
		font-weight: bold;
		color: #46351b;
		margin-bottom: 28rpx;
	}
	.notice-detail {
		font-size: 28rpx;
		font-weight: 400;
		color: #999999;
		line-height: 36rpx;
		margin-bottom: 50rpx;
	}
	.notice-btn {
		width: 492rpx;
		height: 70rpx;
		line-height: 70rpx;
		// background: linear-gradient(90deg, #2dae9c, #6bc29e);
		// box-shadow: 0 7rpx 11rpx 2rpx rgba(61, 179, 156, 0.34);
		background: linear-gradient(-90deg, #57ce16 0%, #88DD18 100%);
		box-shadow: 0px 7rpx 6rpx 0px rgba(205, 251, 176, 0.22);
		border-radius: 35rpx;
		font-size: 28rpx;
		font-weight: 500;
		color: #ffffff;
		margin-bottom: 10rpx;
	}
	.back-btn {
		width: 492rpx;
		height: 70rpx;
		line-height: 70rpx;
		font-size: 28rpx;
		font-weight: 500;
		color: #57ce16;
		background: none;
	}
}

.cu-form-group {
	padding: 0 25rpx;
}
/* 1.1.5升级 */
.cu-form-group.area{
	position: relative;
}
.cu-form-group.area .click{
	position: absolute;
	z-index: 99;
	right: 0;
	left: 0;
	top: 0;
	bottom: 0;
}
.cu-form-group .title {
	min-width: calc(4em + 15px);
	font-size: 26rpx;
}

.cu-form-group input,
.cu-form-group textarea {
	font-size: 26rpx;
}
.tag {
	position: absolute;
	top: 0rpx;
	right: 0rpx;
	z-index: 3;
	display: flex;
	justify-content: center;
	align-items: center;
	text-align: center;
	overflow: hidden;
}
.uploaditem{
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    border-radius: 18rpx;
    overflow: hidden;
    background-color: #f0f0f0;
	width: 200rpx;
	height: 200rpx;
	margin-top: 10px;
}
.cu-form-group-upload{
	padding: 25rpx 25rpx;
	display: flex;
	align-items: flex-start;
	justify-content: flex-start;
	flex-direction: column;
	border-top: 0.5px solid #eee;
}
.position-relative{
	position: relative;
}
.radioSelect{
    transform: scale(0.7);
}

.textarea-style{
	margin-top: 33rpx;
	width: 638rpx;
	height: 199rpx;
	background: #F7F7F7;
	border-radius: 16rpx;
	padding: 27rpx 21rpx;
}

.tipsScroll {
	width: 100%;
	height: 500rpx;
	padding: 0 50rpx;
}

.tipsScroll .item {
	margin: 25rpx 0;
}

.tipsScroll .item view {
	color: #B8B8B8;
	font-size: 22rpx;
}

.tipsScroll .item text {
	color: #333;
}
</style>ss
